
let clickFlag = false
let needLoadingRequestCount = 0;
let loadingTimer;
let EARTH_RADIUS = 6378.137;
import md5 from "./md5.js";

/**
 * @param Number dot
 */
function rad(dot){
	if (typeof dot === 'string') {
		dot = parseFloat(dot)
	}
	return dot * Math.PI / 180.0;
}

function currentTime(){
	let curDate = new Date()
	let year = curDate.getFullYear();
	let month = curDate.getMonth() + 1;
	let day = curDate.getDate();
	let hour = curDate.getHours();
	let minute = curDate.getMinutes();
	let second = curDate.getSeconds();
	let milliSeconds = curDate.getMilliseconds();
	let _fixZero = function(num, n=2) {
		return (Array(n).join(0) + num).slice(-n);
	}
	return year+_fixZero(month)+_fixZero(day)+_fixZero(hour)+_fixZero(minute)+_fixZero(second)+_fixZero(milliSeconds,3)
}

Date.prototype.format = function (fmt) {
    let o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "h+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

let _tool = {
	
	promisic (func) {
	  return function (params = {}) {
	    return new Promise((resolve, reject) => {
	      const args = Object.assign(params, {
	        success: (res) => {
	          resolve(res);
	        },
	        fail: (error) => {
	          reject(error);
	        }
	      });
	      func(args);
	    });
	  };
	},
	
	/*
	 * obj 转 路由地址带参数
	 * 例子：{a:1,b:2} => /pages/index/index?a=1&b=2
	 */
	objParseUrlAndParam(path, obj) {
		let url = path || "/";
		let paramsStr = "";
		if (obj instanceof Array) return url;
		if (!(obj instanceof Object)) return url;
		paramsStr = this.objParseParam(obj);
		paramsStr && (url += "?");
		url += paramsStr;
		return url;
	},
	
	/*
	 * obj 转 params字符串参数  
	 * 例子：{a:1,b:2} => a=1&b=2
	 */
	objParseParam(obj) {
		let paramsStr = "";
		if (obj instanceof Array) return paramsStr;
		if (!(obj instanceof Object)) return paramsStr;
		for (let key in obj) {
			paramsStr += `${key}=${obj[key]}&`;
		}
		return paramsStr.substring(0, paramsStr.length - 1);
	},
	
	/*
	 * 登录后重定向  
	 * 例子：/pages/main/login/login?redirectUrl=/pages/mine/notice&a=1
	 * return /pages/mine/notice?a=1
	 */
	reloadLoginPath(loginPath) {
		let paramsStr = loginPath.split('?')[1];
		let paramsArr = paramsStr.split('&');
		
		var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
		var r = paramsStr.match("redirectUrl");
		if(r!=null){
			return unescape(r[2])
		}  
		return null;
	},
	
	/**
	 * 设置手机通知栏字体颜色
	 */
	setBarColor(black = false) {
		// #ifdef APP-PLUS
		if(black) {
			uni.setNavigationBarColor({
			    frontColor: '#000000',
			    backgroundColor: '#FAFAFA'
			});
		} else {
			uni.setNavigationBarColor({
			    frontColor: '#ffffff',
			    backgroundColor: '#FAFAFA'
			});
		}
		// #endif
	},

	async getSystemSize (cb) {
		uni.getSystemInfo({
			success: function(res) {
				cb && cb( {
					windowHeight: res.windowHeight,
					windowWidth:res.windowWidth,
					screenWidth: res.screenWidth,
					screenHeight: res.screenHeight,
				})
			}
		})

	},
	
	getCurTime() {
		return currentTime();
	},
	
	/**
	 * 签名
	 */
	getMacMD5(username, timestamp) {
		let md5One = md5.hex_md5(username + timestamp) + "dswfewsfewr"
		return md5.hex_md5(md5One)
	},
	
	/**
	 * 获取状态栏和自定义导航栏高度
	 */
	getBarHeight(cb) {
		uni.getSystemInfo({
			success: function(e) {
				const systemInfo = e;
				let navigationBarHeight;
				let custom = {};
				// #ifndef MP
				custom = {height: 36,width: 88};
				navigationBarHeight = 44;
				// #endif
				// #ifdef MP-WEIXIN
				custom = wx.getMenuButtonBoundingClientRect();
				navigationBarHeight = custom.bottom + custom.top - e.statusBarHeight * 2;
				// #endif	
				systemInfo.custom = custom;
				systemInfo.navigationBarHeight = navigationBarHeight;

				
				cb && cb(systemInfo)
			}
		})
	},
	
	
	/**
	 * 计算两个坐标点之间的距离，单位kM
	 * @param lat1	//实际坐标点
	 * @param lng1	//实际坐标点
	 * @param lat2 //目标坐标点
	 * @param lng2  //目标坐标点
	 * @return 返回的是kM
	 */
	getDistance(lat1, lng1, lat2, lng2) {
		let radLat1 = rad(lat1);
		let radLat2 = rad(lat2);
		let a = radLat1 - radLat2;
		let b = rad(lng1) - rad(lng2);
		let s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2)
				+ Math.cos(radLat1) * Math.cos(radLat2)
				* Math.pow(Math.sin(b / 2), 2)));
		s = s * EARTH_RADIUS;
		s = Math.round(s * 10000) / 10000;
		return s;
	},
	
	
	/**
	 * 获取当前路由
	 */
	getCurrentPageUrlWithArgs() {
		// eslint-disable-next-line no-undef
		const pages = getCurrentPages()
		const currentPage = pages[pages.length - 1]
		const url = currentPage.route
		const options = currentPage.options
		let urlWithArgs = `/${url}?`
		for (let key in options) {
			const value = options[key]
			urlWithArgs += `${key}=${value}&`
		}
		urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1)
		return urlWithArgs
	},


	/**
	 * 模态框
	 */
	showModal(option) {
		console.log(clickFlag);
		if (clickFlag) {
			return;
		}
		clickFlag = true;
		option.complete = () => {
			console.log(clickFlag);
			loadingTimer = setTimeout(() => {
				clickFlag = false;
			}, 200)
		}
		uni.showModal(option)
	},
	
	/**
	 * 提示框
	 */
	showToast(option) {
		if (clickFlag) {
			return;
		}
		clickFlag = true;
		option.complete = () => {
			console.log(clickFlag);
			loadingTimer = setTimeout(() => {
				clickFlag = false;
			}, 200)
		}
		uni.showToast(option)
	},
	
	/**
	 * loading show
	 */
	showLoading(title = '', mask = true) {
		if (needLoadingRequestCount === 0) {
			uni.showLoading({
				title,
				mask
			});
	 
			// 最长10s自动关闭
			loadingTimer = setTimeout(() => {
				if (needLoadingRequestCount > 0) {
					uni.hideLoading();
				}
			}, 10000);
		}
		needLoadingRequestCount++;
	},
	
	
	/**
	 * loading hide
	 */
	hideLoading() {
		if (needLoadingRequestCount <= 0) return;
	 
		needLoadingRequestCount--;
	 
		if (needLoadingRequestCount === 0) {
	        loadingTimer && clearTimeout(loadingTimer);
			uni.hideLoading();
		}
	}
	
};

export default _tool;